<template>
  <label
    :for="id"
    class="browser-upload"
    v-loading.fullscreen.lock="fullscreenLoading"
  >
    <slot>
      <p>请上传文件</p>
    </slot>
    <input :id="id" hidden type="file" @change="changeFile" />
  </label>
</template>
<script>
import { uploadFile, isFileOver100KB, generateUUID } from "./obsbrowserjs";
export default {
  name: "BrowserjsUpload",
  data() {
    return {
      baseUrl: "https://cdjiuren.com/mf/",
      fullscreenLoading: false,
      id: "random_id_",
    };
  },
  created() {
    this.id = "random_id_" + generateUUID();
  },
  methods: {
    changeFile() {
      this.$emit("beforeUpload");
      const file = document.getElementById(this.id);
      const currentFile = file?.files?.[0];
      if (!currentFile) return;
      if (isFileOver100KB(currentFile)) {
        this.fullscreenLoading = true;
      }
      uploadFile({
        file: currentFile,
        success: (res) => {
          console.log("url:", `${this.baseUrl}${res}`);
          this.$emit("success", `${this.baseUrl}${res}`);
          this.fullscreenLoading = false;
        },
        fail: (err) => {
          console.log(err);
          this.$emit("fail", err);
          this.fullscreenLoading = false;
        },
      });
    },
  },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
